import _ from 'underscore';
import ClassifyDialogTpl from './classify-dialog.html';
import ClassifyItemTpl from './tpl/classify_item.html';
import './classify-dialog.scss';

import Util from '../util/util.js';
import API from '../../api/Api';
/**
 * Created with JetBrains WebStorm.
 * User: xiongpeng
 * Date: 2017/11/13
 * Time: 上午9:44
 * Desc: 商品分类选择弹窗封装
 * callback 确定按钮回调函数
 */
export default function ClassifyDialog(callback) {
    let classifyObj = {
        data: [],
        checkSub: {
            firstIndex: undefined,
            secondIndex: undefined,
            thirdIndex: undefined
        },
        /**
         * 初始化
         */
        init: function(){
            let _this = this;
            $(".classify-dialog").remove();
            $("body").append( ClassifyDialogTpl );
            this.getData(function(data){
                _this.dataAll = data;
                _this.data = data;
                $(".classify-dialog .opt-wrapper").eq(0).append( ClassifyItemTpl({classifyData: data, index: 0}) )
            });
            this.bindEvent();
        },
        /**
         * 事件绑定
         */
        bindEvent: function(){
            let _this = this;
            //确认
            $(".classify-dialog .confirm").on('click',function(){
                let checkedDatas = _this.getCheckedDatas(_this.data);
                callback(checkedDatas);
                _this.close();
            });
            //关闭
            $(".classify-dialog .cancel,.classify-dialog .icon-shanchu").on('click',function(){
                _this.close();
            });

            $(".search-input").on('keyup',function(e){//搜索
                _this.searchRenderData.call(_this,$(this));
            });

            $(".classify-dialog")
            .on('change','input[type="checkbox"]',function(){//勾选/取消勾选
                _this.checkClassify.call(_this,$(this));
            })
            .on('click','li',function(e){//展开/收起
                if($(e.target).is('input')){
                    return;
                }
                _this.unfoldClassify.call(_this,$(this));
            })
        },
        /**
         * 搜索品类并重新渲染
         * @param $el
         */
        searchRenderData: function($el){
            let rowData = [];
            let filterData = [];
            let rowIndex = $el.data('grade');
            let searchInfo = $el.val();
            let $rowEls = $(".opt-wrapper");
            let $searchInput = $(".search-input");
            let { firstIndex, secondIndex, thirdIndex } = this.checkSub;

            switch(rowIndex){
                case 0:
                    rowData = this.dataAll;
                    //重置dome及参数
                    $rowEls.eq(1).html('');
                    $rowEls.eq(2).html('');
                    $rowEls.eq(3).html('');
                    $searchInput.eq(1).val('');
                    $searchInput.eq(2).val('');
                    $searchInput.eq(3).val('');
                    this.checkSub.firstIndex = undefined;
                    this.checkSub.secondIndex = undefined;
                    this.checkSub.thirdIndex = undefined;
                    break;
                case 1:
                    rowData = this.data[firstIndex].children;
                    $rowEls.eq(2).html('');
                    $rowEls.eq(3).html('');
                    $searchInput.eq(2).val('');
                    $searchInput.eq(3).val('');
                    this.checkSub.secondIndex = undefined;
                    this.checkSub.thirdIndex = undefined;
                    break;
                case 2:
                    rowData = this.data[firstIndex].children[secondIndex].children;
                    $rowEls.eq(3).html('');
                    $searchInput.eq(3).val('');
                    this.checkSub.thirdIndex = undefined;
                    break;
                case 3:
                    rowData = this.data[firstIndex].children[secondIndex].children[thirdIndex].children;
                    break;
            }

            filterData = this.filterData(rowData,searchInfo);
            if(rowIndex == 0){
                this.data = filterData;
            }
            $rowEls.eq(rowIndex).html( ClassifyItemTpl({classifyData: filterData, index: rowIndex}) );
        },
        /**
         * 获取选中品类的id、name对象数组
         * @param data
         * @returns {Array}
         */
        getCheckedDatas: function(data){
            let checkedArr = [];
            data.map((item,index) => {
                item.checked && item.level == 4 && checkedArr.push(item);
                if(item.children && item.children.length){
                    let childCheckedArr = this.getCheckedDatas(item.children);
                    checkedArr = checkedArr.concat(childCheckedArr);
                }
            });

            return checkedArr;
        },
        /**
         * 展开/收起子品类
         * @param $el
         */
        unfoldClassify: function($el){
            let childrenData = [];
            let id = $el.data('id');
            let $rowEls = $(".opt-wrapper");
            let index = $el.data('index');
            let rowIndex = $el.parent().data('index');
            let { firstIndex, secondIndex, thirdIndex } = this.checkSub;

            if($el.hasClass('unfold')){//收起
                return;
            }else{//展开
                switch(rowIndex){
                    case 0:
                        $rowEls.eq(2).html('');
                        $rowEls.eq(3).html('');
                        this.checkSub.firstIndex = index;
                        this.checkSub.secondIndex = undefined;
                        this.checkSub.thirdIndex = undefined;
                        childrenData = this.data[index].children;
                        $rowEls.eq(1).html( ClassifyItemTpl({classifyData: childrenData, index: 1}) );
                        break;
                    case 1:
                        $rowEls.eq(3).html('');
                        this.checkSub.secondIndex = index;
                        this.checkSub.thirdIndex = undefined;
                        childrenData = this.data[firstIndex].children[index].children;
                        $rowEls.eq(2).html( ClassifyItemTpl({classifyData: childrenData, index: 2}) );
                        break;
                    case 2:
                        this.checkSub.thirdIndex = index;
                        childrenData = this.data[firstIndex].children[secondIndex].children[index].children;
                        $rowEls.eq(3).html( ClassifyItemTpl({classifyData: childrenData, index: 3}) );
                        break;
                }
                $el.parent().find('li').removeClass('unfold');
                $el.addClass('unfold');
            }
        },
        /**
         * 勾选品类
         * @param $el
         */
        checkClassify: function($el){
            let checkData = {};
            let checked = $el[0].checked;
            let rowIndex = $el.parents('ul').data('index');
            let index = $el.parent().data('index');
            let id = $el.parent().data('id');
            let { firstIndex, secondIndex, thirdIndex } = this.checkSub;

            switch(rowIndex){
                case 0:
                    checkData = this.data[index];
                    break;
                case 1:
                    checkData = this.data[firstIndex].children[index];
                    break;
                case 2:
                    checkData = this.data[firstIndex].children[secondIndex].children[index];
                    break;
                case 3:
                    checkData = this.data[firstIndex].children[secondIndex].children[thirdIndex].children[index];
                    break;
            }

            checkData.checked = checked;
            checkData.halfChecked = false;
            this.checkChildren(checkData,checked);
            this.checkParent(rowIndex,checked);
            this.renderRow(rowIndex);

        },
        /**
         * 处理子品类选中/取消选中
         * @param data
         * @param checked
         */
        checkChildren: function(data,checked){
            if(!data.children || !data.children.length){
                return;
            }

            data.children.map((item,index) => {
                item.checked = checked;
                item.halfChecked = false;
                this.checkChildren(item,checked);
            })
        },
        /**
         * 处理父品类选中/取消选中
         * @param rowIndex
         * @param checked
         */
        checkParent: function(rowIndex,checked){
            if(rowIndex == 0){
                return;
            }

            let parentData = {}; //父品类对象
            let childrenData = []; //所有父品类下的子品类
            let { firstIndex, secondIndex, thirdIndex } = this.checkSub;
            switch(rowIndex){
                case 1:
                    parentData = this.data[firstIndex];
                    break;
                case 2:
                    parentData = this.data[firstIndex].children[secondIndex];
                    break;
                case 3:
                    parentData = this.data[firstIndex].children[secondIndex].children[thirdIndex];
                    break;
            }

            let checkedAll = true; //初始化全选
            let halfChecked = false; //初始化非半选
            childrenData = parentData.children;
            childrenData.map((item,index) => {
                if(!item.checked){
                    checkedAll = false;
                }
                if(item.checked || item.halfChecked){
                    halfChecked = true;
                }
            });
            if(checked){
                parentData.checked = checkedAll;
                parentData.halfChecked = checkedAll ? false : halfChecked;
                rowIndex > 1 && this.checkParent(rowIndex - 1, checkedAll);
            }else{
                parentData.checked = false;
                parentData.halfChecked = halfChecked;
                rowIndex > 1 && this.checkParent(rowIndex - 1, false);
            }
        },
        /**
         * 重新渲染品类模板
         * @param checkedIndex
         */
        renderRow: function(checkedIndex){
            let $rowEls = $(".opt-wrapper");
            let $searchInput = $(".search-input");
            let firstInputVal = $searchInput.eq(0).val();
            let secondInputVal = $searchInput.eq(1).val();
            let thirdInputVal = $searchInput.eq(2).val();
            let fourthInputVal = $searchInput.eq(3).val();
            let { firstIndex, secondIndex, thirdIndex } = this.checkSub;

            switch(checkedIndex){
                case 0:
                    firstIndex !== undefined && $rowEls.eq(1).html( ClassifyItemTpl({
                        //先对数据进行过滤处理
                        classifyData: this.filterData(this.data[firstIndex].children,secondInputVal),
                        index: 1,
                        unfoldIndex: secondIndex
                    }) );
                    secondIndex !== undefined && $rowEls.eq(2).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children[secondIndex].children,thirdInputVal),
                        index: 2,
                        unfoldIndex: thirdIndex
                    }) );
                    thirdIndex !== undefined && $rowEls.eq(3).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children[secondIndex].children[thirdIndex].children,fourthInputVal),
                        index: 3
                    }) );
                    break;
                case 1:
                    $rowEls.eq(0).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data,firstInputVal),
                        index: 0,
                        unfoldIndex: firstIndex
                    }) );
                    $rowEls.eq(1).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children,secondInputVal),
                        index: 1,
                        unfoldIndex: secondIndex
                    }) );
                    secondIndex !== undefined && $rowEls.eq(2).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children[secondIndex].children,thirdInputVal),
                        index: 2,
                        unfoldIndex: thirdIndex
                    }) );
                    thirdIndex !== undefined && $rowEls.eq(3).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children[secondIndex].children[thirdIndex].children,fourthInputVal),
                        index: 3
                    }) );
                    break;
                case 2:
                    $rowEls.eq(0).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data,firstInputVal),
                        index: 0,
                        unfoldIndex: firstIndex
                    }) );
                    $rowEls.eq(1).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children,secondInputVal),
                        index: 1,
                        unfoldIndex: secondIndex
                    }) );
                    $rowEls.eq(2).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children[secondIndex].children,thirdInputVal),
                        index: 2,
                        unfoldIndex: thirdIndex
                    }) );
                    thirdIndex !== undefined && $rowEls.eq(3).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children[secondIndex].children[thirdIndex].children,fourthInputVal),
                        index: 3
                    }) );
                    break;
                case 3:
                    $rowEls.eq(0).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data,firstInputVal),
                        index: 0,
                        unfoldIndex: firstIndex
                    }));
                    $rowEls.eq(1).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children,secondInputVal),
                        index: 1,
                        unfoldIndex: secondIndex
                    }) );
                    $rowEls.eq(2).html( ClassifyItemTpl({
                        classifyData: this.filterData(this.data[firstIndex].children[secondIndex].children,thirdInputVal),
                        index: 2,
                        unfoldIndex: thirdIndex
                    }) );
                    break;
            }

            //半选渲染
            $("input[data-type='indeterminate']").each(function(i){
                this.indeterminate = true;
            });
            $("input[data-type='other']").each(function(i){
                this.indeterminate = false;
            });
        },
        /**
         * 数据过滤
         * @param data
         * @param filterVal
         * @returns {Array}
         */
        filterData: function(data,filterVal){
            let newData = [];

            data.length && data.map((item,index) => {
                if(item.categoryName.indexOf(filterVal) > -1){
                    newData.push(item);
                }
            });

            return newData;
        },
        /**
         * 获取品类数据
         * @param callback
         */
        getData: function(callback){
            $.ajax({
                url: API.cateTree,
                type: 'get',
                success(data) {
                    let {result: { children }, success} = data;
                    if(success){
                        callback(children);
                    }
                }
            });
        },
        close: function(){
            $(".classify-dialog").remove();
        }
    }

    classifyObj.init();
    return classifyObj;
}